package com.biz.primus.ms.commodity.trans;

import com.biz.primus.commodity.vo.frontend.RapidProductItemVo;
import com.biz.primus.common.utils.DateUtil;
import com.biz.primus.common.utils.JsonUtils;
import com.biz.primus.ms.commodity.dao.po.GroupProduct;
import com.biz.primus.ms.commodity.dao.po.GroupProductItem;
import com.biz.primus.ms.commodity.dao.po.Product;
import com.biz.primus.ms.commodity.dao.po.ProductStatistic;
import com.biz.primus.ms.commodity.dao.repository.brand.BrandRepository;
import com.biz.primus.ms.commodity.dao.repository.category.CategoryRepository;
import com.biz.primus.ms.commodity.dao.ro.ProductRo;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Optional;


/**
 * 转换器(Product --> ProductRo)
 *
 * @author david-liu
 * @date 2017年02月24日
 * @reviewer
 */
public class Product2ProductRo implements Function<Product, ProductRo> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private BrandRepository brandRepository;

    private CategoryRepository categoryRepository;

    public Product2ProductRo(BrandRepository brandRepository, CategoryRepository categoryRepository) {
        this.brandRepository = brandRepository;
        this.categoryRepository = categoryRepository;
    }

    @Override
    public ProductRo apply(Product po) {
        ProductRo ro = new ProductRo();
        ro.setId(po.getProductCode());
        ro.setVendorId(po.getVendorId());
        ro.setProductCode(po.getProductCode());
        ro.setName(po.getName());
        ro.setSubTitle(po.getSubTitle());
        ro.setSubHeadingMark(po.getSubHeadingMark());
        ro.setBreif(po.getBreif());
        ro.setExtendProduct(po.getExtendProduct());
        ro.setBrandId(po.getBrandId());
        if (brandRepository!=null&&po.getBrandId()!=null){
            Optional.ofNullable(brandRepository.findOne(po.getBrandId()))
                    .ifPresent(b->ro.setBrandName(b.getName()));
        }
        ro.setCategoryId(po.getCategoryId());
        if (categoryRepository!=null&&po.getCategoryId()!=null){
            Optional.ofNullable(categoryRepository.findOne(po.getCategoryId()))
                    .ifPresent(c->ro.setCategoryName(c.getName()));
        }
        if (CollectionUtils.isNotEmpty(po.getIntroImages())) {
            ro.setIntroImages(StringUtils.join(po.getIntroImages(), ","));
        }
        ro.setLogo(po.getLogo());
        ro.setSaleTagIds(po.getSaleTagIds());
        ro.setSeoKeywords(po.getSeoKeywords());
        if (CollectionUtils.isNotEmpty(po.getImages())) {
            ro.setImages(StringUtils.join(po.getImages(), ","));
        }
        ro.setProductId(po.getId());
        ro.setProductType(po.getProductType().getValue());
        ro.setOnSaleTime(DateUtil.now());
        boolean isRapidProduct = po.getIsRapidProduct() != null && po.getIsRapidProduct();
        ro.setIsRapidProduct(isRapidProduct);
        ro.setSaleStatus(po.getSaleStatus().getValue());
        ro.setAppSaleStatus(po.getAppSaleStatus().getValue());
        ro.setWebSaleStatus(po.getWebSaleStatus().getValue());
        String errorMsg = "";
        if (isRapidProduct) {
            try {
                GroupProduct groupProduct = po.getGroupProduct();
                if (groupProduct == null){
                    errorMsg += "groupProduct不存在;";
                }
                Preconditions.checkArgument(groupProduct != null && CollectionUtils.isNotEmpty(groupProduct.getItemList()));
                List<RapidProductItemVo> rapidProductItemVoList = Lists.newArrayList();
                List<GroupProductItem> groupProductItems = groupProduct.getItemList();
                for (GroupProductItem groupProductItem : groupProductItems) {
                    RapidProductItemVo rapidProductItemVo = new RapidProductItemVo();
                    rapidProductItemVo.setProductCode(groupProductItem.getProduct().getProductCode());
                    rapidProductItemVo.setQuantity(groupProductItem.getQuantity());
                    rapidProductItemVo.setPriceFactor(groupProductItem.getPriceFactor());
                    rapidProductItemVoList.add(rapidProductItemVo);
                }
                ro.setRapidProductInfo(JsonUtils.obj2Json(rapidProductItemVoList));
            }catch (Exception e){
                logger.info("组合商品异常 productCode = {} ,原因:{}",errorMsg + e.getMessage());
                return null;
            }
        }
        ro.setWeight(po.getWeight());
        ProductStatistic productStatistic = po.getProductStatistic();
        if (productStatistic != null){
            if (productStatistic.getVirtualSalesVolume() != null && productStatistic.getVirtualSalesVolume() > 0){
                ro.setSalesVolume(Optional.of(productStatistic.getVirtualSalesVolume()).orElse(0));
            }else {
                ro.setSalesVolume(Optional.of(productStatistic.getTotalSalesVolume()).orElse(0));
            }
            ro.setScore(Optional.of(productStatistic.getProductScore()).orElse(0));
            ro.setScoreCount(Optional.of(productStatistic.getEvaluationCount()).orElse(0));
            ro.setViewVolume(Optional.of(productStatistic.getTotalViewVolume()).orElse(0));
        }
        if (po.getPackageNumber()!=null&&po.getPackageNumber()>1){
            ro.setPackageNumber(po.getPackageNumber());
        }
        ro.setGlobalIdx(po.getGlobalIdx());
        return ro;
    }
}
